import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import {Button, Card, Col, Divider, Form, Input, Modal, Row} from 'antd';
// import StandardTable from '@/components/StandardTable';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import MoveFileForm from '../Filecenter/sub/MoveFileForm';
import styles from './ReceiveList.less';
import {getReadableSize, hasInstalledEditApp,} from '@/utils/dsrsUtil';

const FormItem = Form.Item;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');


/* eslint react/no-multi-comp:0 */
@connect(({receiveModel, loading}) => ({
  receiveModel,
  loading: loading.models.receiveModel,
}))
@Form.create()
class ReceiveList extends PureComponent {
  state = {
    selectedRows: [],
    formValues: {},
    moveModalVisible: false,
    hidefunctions: [],
  };

  columns = [
    {
      title: '文件名称',
      dataIndex: 'fileName',
      width: "30%",
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
      // render: record => <a onClick={() => this.previewItem(record)}>{record.fileName}</a>,
    },
    {
      title: '文件大小',
      dataIndex: 'fileSize',
      render: (text, record) => {
        if (text) {
          return getReadableSize(text * 1024);
        } else {
          return '--'
        }
      },
    },
    {
      title: '流转人',
      dataIndex: 'orignFileUserName',
    },
    {
      title: '流转时间',
      dataIndex: 'createTime',
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '操作',
      render: (text, record) => {
        const {hidefunctions} = this.state;
        let hidePreview = false;
        let hideEdit = false;
        let hideDownload = false;
        hidefunctions.forEach(item=>{

          if(item=='function_hide_preview'){
            hidePreview = true;
          }else if(item=='function_hide_edit'){
            hideEdit = true;
          }else if(item=='function_hide_download'){
            hideDownload = true;
          }
        })
        return <Fragment>
          {/*<a onClick={() => this.previewItem(record)}>预览</a>*/}
          {/*<Divider type="vertical"/>*/}
          <a onClick={() => this.deleteData(text.id)}>删除</a>
          <Divider type="vertical"/>
          {/*<Popconfirm title="是否要下载此文件？" onConfirm={() => this.preDownloadItem(record)}>
            <a>下载</a>
          </Popconfirm>*/}
          {hideDownload?null:<a onClick={() => this.isDownload(record)}>下载</a>}

          <Divider type="vertical"/>
          <a onClick={() => this.handleMoveModalVisible(true, record)}>移动</a>
        </Fragment>
      },
    },
  ];

  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleDeleteData(id),
    });
  };

  // 删除方法
  handleDeleteData(ids) {
    const {dispatch} = this.props;
    dispatch({
      type: 'receiveModel/delete',
      payload: {ids},
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.myFetch();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  componentDidMount() {
    this.myFetch();
    // 查询需要隐藏的按钮，放在这里不合适，先这么做
    this.queryHideFunctions();
  }
  queryHideFunctions = () => {
    const {dispatch} = this.props;

    let params = {dataDictTypeCode: 'function_hide', status: 0};
    dispatch({
      type: 'receiveModel/queryHideFunctions',
      payload: params,
      callback: (res) => {
        if (res.result == "ok" && res.data) {

          let valuesArray = [];
          //把需要隐藏的筛选出来
          res.data.dataList.forEach(item => {
            if (item.dataDictValue == '1') {
              valuesArray.push(item.dataDictCode);
            }
          })

          this.setHideFunctions(valuesArray);
        }
      },
    });
  };
  setHideFunctions = (values) => {
    this.setState({hidefunctions: values});

  }
  queryDirTreeList(userCode) {
    const {dispatch} = this.props;
    dispatch({
      type: 'receiveModel/queryDirTreeList',
      payload: {userCode},
    });
  }

  myFetch(data, pageSize = 10, pageNum = 0) {
    const {dispatch} = this.props;
    const values = {
      fileName: data && data.fileName || '',
      orignFileUserName: data && data.orignFileUserName || '',
      pageSize: pageSize, //分页每页条数
      pageNum: pageNum, //分页页码
    };
    dispatch({
      type: 'receiveModel/receivefilesList',
      payload: values,
    });
  }

  /**
   * 移动文件弹出框
   * @param flag
   * @param record
   */
  handleMoveModalVisible = (flag, record) => {
    if (flag) {
      this.queryDirTreeList(record.userCode);
    }

    this.setState({
      moveModalVisible: !!flag,
      record: record || {},
    });
  };

  handleMove = (id, record) => {
    const {dispatch} = this.props;
    const params = {
      id: record.id,
      parentId: id,
    }
    dispatch({
      type: 'receiveModel/moveFile',
      payload: params,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.handleMoveModalVisible();
          this.myFetch();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }


  isDownload = record => {
    Modal.confirm({
      title: '下载',
      content: '您确定要下载吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.preDownloadItem(record),
    });
  }

  preDownloadItem = record => {
    const {dispatch} = this.props;
    dispatch({
      type: 'receiveModel/downloadFiles',
      payload: {
        id: record.id,
      },
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const {formValues} = this.state;
    // 分页请求
    this.myFetch(formValues, pagination.pageSize, pagination.current - 1);
  };

  previewItem = record => {

    if (!hasInstalledEditApp()) {
      //如果没有安装客户端，下载在线编辑客户端
      Modal.warning({title: '请先下载安装在线编辑客户端'});
      this.downloadBwdaOnlineEdit();
      return;
    }

    const params = {
      id: record.id,
    }
    this.previewFile(params)
  };
  downloadBwdaOnlineEdit = () => {
    window.open("/DSRS-OnlineEdit.exe", "_self");
  }
  previewFile(params) {
    const {dispatch} = this.props;
    dispatch({
      type: 'receiveModel/previewFile',
      payload: params,
      callback: (res) => {
        if (res.result == "ok") {
          let path = res.data;
          if (path) {
            window.open(path, "_self");
          } else {
            Modal.error({title: '操作失败', content: "缺少路径，无法预览"});
          }
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const {dispatch, form} = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });
      this.myFetch(values)

    });
  };


  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="文件名称">
              {getFieldDecorator('fileName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      receiveModel: {data, dirTreeList,},
      loading,
    } = this.props;
    const {selectedRows, moveModalVisible, record,} = this.state;
    //移动文件
    const moveMethods = {
      handleMove: this.handleMove,
      handleModalVisible: this.handleMoveModalVisible,
    };


    return (
      <PageHeaderWrapper title="我的接收">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>

            <TableList
              className={styles.tdPadding}
              hideRowSelection={true}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              rowKey={record => record.id}
            />
          </div>
        </Card>
        <MoveFileForm
          {...moveMethods}
          modalVisible={moveModalVisible}
          record={record}
          dirTreeList={dirTreeList}
        />
      </PageHeaderWrapper>
    );
  }
}

export default ReceiveList;
